<?php
/**
 * Created by PhpStorm.
 * User: woody
 * Date: 18-10-8
 * Time: 下午2:07
 */
namespace App\Http\Controllers\Api;
use App\Blocks\User;
use App\Models\Vipusermarketapi;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Session;

class LoginwechatController extends ApiController {

    public function __construct()
    {
        parent::__construct();
        $this->_response['_active']['_model']       = 'vipuser';
        $this->_response['_active']['_action']      = '';
        $this->_response['_title']                  = '小一农货-授权登录接口';

    }

    public function weixinCallback(Request $request){
        $config = \Config::get('wechat');

        dd($config);
        \Log::debug($config);
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $user = $oauth->user();

        $userBlock = new User();
        $userInfo = $userBlock->getUserByWxOpenid($user->getId());
        if(!$userInfo){
            $wxuser = $user->getOriginal();
            \Log::debug(json_encode($wxuser));
            global $wechatId;

            $saveUserData = [
                'wechat_id'         => $wechatId,
                'subscribe_time'    => isset($wxuser['subscribe_time'])?date('Y-m-d H:i:s', $wxuser['subscribe_time']):null,
                'openid'            => $wxuser['openid'],
                'nickname'          => isset($wxuser['nickname'])?$wxuser['nickname']:null,
                'city'              => isset($wxuser['city'])?$wxuser['city']:null,
                'province'          => isset($wxuser['province'])?$wxuser['province']:null,
                'country'           => isset($wxuser['country'])?$wxuser['country']:null,
                'sex'               => isset($wxuser['sex'])?$wxuser['sex']:null,
                'headimgurl'        => isset($wxuser['headimgurl'])?$wxuser['headimgurl']:null,
                'subscribe'         => isset($wxuser['subscribe'])?$wxuser['subscribe']:0,
                'create_time'       => date('Y-m-d H:i:s', time()),
            ];
            $userId = $userBlock->saveUserByWeixin($saveUserData);

            if($userId){
                $userInfo = [
                    'openid' => $saveUserData['openid'],
                    'wx_openid' => $saveUserData['openid'],
                    'headimgurl' => $saveUserData['headimgurl'],
                    'nick_name' => $saveUserData['nickname'],
                    'mobile' => null,
                    'id' => $userId,
                ];

                $userInfo = (object)$userInfo;
            }
        }

        if(isset($userInfo->id)){
            if(isset($userInfo->create_time)){
                unset($userInfo->create_time);
            }

            $sessionKey = md5($userInfo->wx_openid);
            \Cache::put($sessionKey, $userInfo, \Config::get('session.lifetime'));
            $cookie = \Cookie::make(\Config::get('session.user_cookie'), $sessionKey, \Config::get('session.lifetime'));

            $userInfo->token = $sessionKey;

            if($request->has('redirect')){
                $redirect = $request->get('redirect');
                $url = env('WEB_URL').'/index';
                if($url === $redirect){
                    $url = env('WEB_URL').'/index';
                }

                $url .= "?token={$userInfo->token}";
                return redirect($url)->withCookie($cookie);
            }
            return response()->json($userInfo)->withCookie($cookie);
        }else{
            return response()->json(['error' => '登录失败']);
        }
    }


    public function getbaseinfo(){
           // $vip_id=$_GET['vip_id'];
            $appid="wxbb745d806aa9cdcb";
            $redirect_uri=urlencode("http://fitment.guoxiaoge.cn/api/openid");
            $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            header('location:'.$url);

    }

    public function  getopenid(){
            $appid="wxbb745d806aa9cdcb";
            $appsecret="af66340dc225f289a510b92db48c06b3";
            $code=$_GET['code'];
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
            $res=file_get_contents($url);
            $data=explode(',',$res);
            var_dump($res);
            print_r($data);
           // exit;
            $use_url="https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid'];
            $useinfo=file_get_contents($use_url);
            $info=json_decode($useinfo,true);
            $saveData = [
                'user_id' => $info['openid'],
                'vip_id'=>1,
                'user_name' => $info['nickname'],
                'user_level' => '普通会员',
                'avatar'=>$info['headimgurl'],
                'created_at' => date('Y-m-d H:i:s', time()),
            ];
        Session::put('openid',$data['openid']);
        $vipusermarketModel = new Vipusermarketapi();
        if($vipusermarketModel->saveData($saveData)){
            return response()->json(['code' => 0, 'msg' => '添加成功']);
        }else{
            return response()->json(['code' => -1, 'msg' => '添加失败']);
        }
           // print_r($saveData);

    }

    public  function test(){
//        $data=\DB::table('roomdata')->get();
//
//        print_r($data);
        $weather = curl_init();
        curl_setopt($weather,CURLOPT_URL,"https://api.pc2801.com/cqssc/".time());
        curl_setopt($weather, CURLOPT_SSL_VERIFYPEER, false); //如果接口URL是https的,我们将其设为不验证,如果不是https的接口,这句可以不用加
        curl_setopt($weather,CURLOPT_RETURNTRANSFER,true);
        $data = curl_exec($weather);
        curl_close($weather);
        $data=json_decode($data,true);//将json格式转化为数组格式,方便使用


    }

    public function map(){
//        坐标拾取工具
//        https://lbs.amap.com/console/show/picker
//        组件产品
//        https://lbs.amap.com/smart/lightmap/guide-2/summary
//        key申请
//        https://lbs.amap.com/console

    }


}